import React,{useState,useRef,useEffect, Fragment} from 'react';
import {useDrag,useDrop} from 'react-dnd';
import ItemTypes from '../daoDemo2/ItemTypes';
import {Curve,CurveShow} from './curve';    
import update from 'immutability-helper';
import {useSelector,useDispatch} from 'react-redux';   // 代替connect
import {addCurveInDao2, getCurvesCount} from '../../../redux/actions';


export const CurveContainer = (props) => {   // 接收curves，每个道中的曲线值
  
  const {daoId, vLine, hLine, leftData} = props;   // 道id、道索引、纵格线状态、横格线状态
  const defaultCurves = props.curves;   // 道中的曲线，只有模板时，xData为空；导入文件后，xData有值；
  //console.log("CurveContainer.js",props,daoId, daoIndex, vLine, hLine,defaultCurves);

  const isDraggable = useSelector(state => state.isDraggable);
  const daosDataList = useSelector(state => state.daosDataList2);   // 从state中取 数据
  const depthDataa = useSelector(state => state.depthDataa2);
  const mb_dao = useSelector(state => state.mbData.mb_dao);
  const chartZoom = useSelector(state => state.gridConfig.chartZoom)

  // 新的curves值，保存时需要更新daosList中的curves；  
  const [curvesList, setCurvesList] = useState(defaultCurves);   //拽过来的组件列表，存有组件, 默认该道中本来有的curve，    
  const [curves, setCurves] = useState(defaultCurves); // 将传入的值作为初始值
  const [count, setCount] = useState(0); // 该文件的各个道中的最多曲线个数

  const dispatch = useDispatch()   // 像state 更改 数据

  const ref = useRef(null);

  var defaultCurvesIdList = [];   // 获取曲线id：这里使用 曲线名（curve_name）作为曲线唯一标识！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
  defaultCurves.map(item => defaultCurvesIdList.push(item.curve_name));  //道中的曲线id: 这里使用 曲线名（curve_name）作为曲线唯一标识
  //console.log("道中的曲线",defaultCurves,defaultCurvesIdList);
  
  useEffect(()=>{
    setCurves([]);
    setCurves(defaultCurves)
  },[JSON.stringify(defaultCurves)])

  const [, drag] = useDrag({   // 拖拽对象    
    item: {
      type: ItemTypes.CURVE_CONTAINER,  
    },
  }) 
  
  const [, drop] = useDrop({   // 定义drop放置目标对象的规则：{ isOver, canDrop  } 是从collect中解构出来的 属性， drag代表usedrag
    accept: ItemTypes.CURVE,   // 可接收拖拽对象的type
    drop: (item) => f(item),  // 当前需要接收的 drag对象 是否可以 放置在此；f()应该是规定放置规则
    collect: monitor => ({
      didDrop: monitor.didDrop(),  // 是否悬浮在drop区域中
    }),
  });


  //当新增曲线后，把state中的曲线列表同步到redux中
  useEffect(()=>{
    daosDataList.map((item) => {
      if(item.id === daoId){
        item.curves = curvesList;
        dispatch(addCurveInDao2(daosDataList));
      }
    });
  },[JSON.stringify(curvesList)])
  


  

  const f = (item) => {   // item:接收的是Item.js中usedrag的item；  定义放置的规则；   
    //console.log('f', item)
    if (item.type === ItemTypes.CURVE) {   // 只有type类型完全一致时，才能响应操作
       //var isExist = curvesIdList.some((ele) => ele === item.id ) //先看组件是否存在于组件名列表里
       //if(!isExist) {  //组件未拖拽过 
      //  console.log("拖过来的曲线",count,item);
        setCurvesList(   // 更新 曲线列表
          update(curvesList, {$push: [item]})
        )
      //}
    }  
    //console.log('更新后道曲线', curvesList);
    //console.log('更新后道曲线id', curvesIdList);
  }  

  

  const renderCurve = (curve, index) => {   // 渲染curve,将属性传给<Dao />
    let id = curve.curve_id ? curve.curve_id + curve.curve_name : Math.random()
    return (
      <Curve
        curve= {curve}
        key={id}
        dao_id={daoId}
        // moveCurve={moveCurve} 
        index = {index}
        // curve_id={curve.curve_id}
        // curve_name={curve.curve_name}
        // title={curve.title}
        // left_data={curve.left_data}
        // right_data={curve.right_data}
        // type={curve.type}
        // data={curve.data}
        // color={curve.color}
        // width={curve.width}  
      />
    )
  }

  


  const renderCurveShow = (curve) => {   // 渲染curve,将属性传给<Dao />
    // console.log(curve,index)
    let id = curve.curve_id ? curve.curve_id + curve.curve_name : Math.random()
    return (
      <CurveShow
        key={id}
        curve= {curve}
        isDraggable = {isDraggable}
      />
    )
  }

  


  let vgridNumber,hgridNumber,hlineType,vlineType,dao_width;
  if(mb_dao){
    mb_dao.map(item=>{
      if(item.id==daoId){
        vgridNumber=item.vgridNumber;
        hgridNumber=item.hgridNumber;
        hlineType=item.hlinetype;
        vlineType=item.vlinetype;
        dao_width=item.dao_width
      }
    })
  }


  

  const hstyle={height:2*chartZoom};
  const hhstyle={height:2*chartZoom/hgridNumber,borderBottomStyle:hlineType }
  
  const vvstyle={ borderRightStyle:vlineType}
  
  const hNumber=(number)=>{
    let arr=[];
    for(let i=0;i<number-1;i++){
      arr.push(
        <div className="hhline" key={i} style={hhstyle} ></div>
      )
    }
    return arr;
  }

  const vNumber=(number)=>{
    let arr=[];
    for(let i=0;i<number;i++){
      arr.push(
        <div className="vline" key={i} style={vvstyle}></div>
      )
    }
    return arr;
  }

  const renderHLine = () => {
    let arr = [];
    for(let i = 0; i <= parseInt((depthDataa[depthDataa.length-1] - depthDataa[0]) / 5); i++){  
      arr.push(<div key={i} className="hline" style={hstyle}>
                  {
                    hNumber(hgridNumber)
                  }
                </div>)    
    }  
    
    return arr;
  }

  
  function getCurveWrapperHeight(){   // 获取 该文件的各个道中的最多曲线个数
    var count1 = 0;
    daosDataList.map((item1) => {
      var daoCount = 0;
      if(item1.curves){
        item1.curves.map(() => {
          daoCount++;
        })
      }
      if(count1 < daoCount){
        count1 = daoCount
      }
    })
    setCount(count1);
    // console.log("最大的曲线数",count1,count);
  }

  useEffect(() => {
    getCurveWrapperHeight();  //实时获取 该文件的各个道中的最多曲线个数
  })

  useEffect(()=>{
    dispatch(getCurvesCount(count));  // 及时更新 曲线最大数，并更新各模块
  },[count])
  
  drag(drop(ref))
  return ( 
    <Fragment>  
      
      <div 
        ref={ref} 
        className="dao-curve-title-wrapper" 
        style={{ 
          width:dao_width-2,
          minHeight: 34, 
          height: count*34,
          left: leftData
        }}   
      >
        <div className="big-curve-title">
          {curvesList.map((curve, i) => renderCurve(curve, i))}    
        </div> 
      </div>
      <div 
          className="curve-show-wrapper" 
          style={{
            width:dao_width-2,
            height: (parseInt((depthDataa[depthDataa.length-1] - depthDataa[0])/ 5)+1)*2*chartZoom 
            }}> 
        { vLine ? (<div className="vgridlines" >
                      {vNumber(vgridNumber)}
                    </div>)
                : null  
        }
        { hLine ? <div className="hgridlines">{renderHLine()}</div> : null }
        {curvesList.map((curve,index) => renderCurveShow(curve,index))}
      </div> 
    </Fragment>    
  )
};